import md5 from 'js-md5'

const baseUrl = 'https://b1.qdqc.wandoujob.cn/api/v1' //服务器地址

export default {
	// 数据请求
	requst(url, data, type = 'GET', contentType = 'application/json', apikey = '54e078e01a55663ccbce928556645798', cid =
		'495702') {

		let header = {
			'Content-type': contentType
		}
		let i = this.generateUUID()

		let token = uni.getStorageSync("token")

		if (token) {
			header.token = token
		}
		let list = {
			i: i,
			ak: md5(apikey + i),
			cid: cid,
			token: uni.getStorageSync("token") || ''
		}
		return new Promise((resolve, reject) => {

			uni.request({
				url: baseUrl + url,
				data: Object.assign(list, data),
				header: header,
				method: type,
				success: (res) => {
					uni.hideLoading()
					if (res.statusCode == 200 || res.statusCode == 201) {
						if (res.data.code == 0) {
							resolve(res.data)
						} else if (res.data.code == 401) {
							uni.removeStorageSync('token')
							// let page = getCurrentPages()
							// if (page[page.length - 1].route !== 'pages/mine/mine') {
							// 	uni.navigateTo({
							// 		url: '/pages/login/login'
							// 	})
							// } else {
							// 	resolve(res.data)
							// }
							uni.redirectTo({
								url: '/pages/login/login'
							})
						} else if (res.data.code == -10) {
							this.showError(res.data.message);
							uni.clearStorageSync()
							uni.redirectTo({
								url: '/pages/login/login'
							})
						} else {
							this.showError(res.data.message);
						}
					} else if (res.statusCode == 401) {
						uni.removeStorageSync('token')
						uni.redirectTo({
							url: '/pages/login/login'
						})
					} else {
						this.showError('服务器错误');
					}

				},
				fail: (err) => {
					console.log("err", err);
					// this.showError('其他错误');
				}
			});
		})

	},

	// 获取随机码
	generateUUID() {
		var d = new Date().getTime();
		var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = (d + Math.random() * 16) % 16 | 0;
			d = Math.floor(d / 16);
			return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
		});
		return uuid;
	},
	/* 通用报错提示*/
	showError(msg) {
		uni.showToast({
			title: msg,
			icon: 'none',
			duration: 2000
		})
	},
	// modal提示
	showModal(msg, cancel = true, title = '提示') {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title: title,
				content: msg,
				showCancel: cancel,
				success: function(res) {
					if (res.confirm) {
						resolve()
					}
				}
			})
		}).catch(err => {
			this.showError('未知错误')
		})
	},
	// 预览图片
	toPreviewImg(img, current = 0) {
		let arr = []
		if (typeof(img) === 'string') {
			arr.push(img)
		} else {
			arr = img
		}
		uni.previewImage({
			urls: arr,
			current: current
		})
	},
	// 富文本图片处理
	formatRichText(html) {
		let newContent = html.replace(/\<img/gi, '<img style="max-width:100% !important;height:auto;display:block;"');
		return newContent;
	},
	// 上传七牛云
	requestUploadQNY(file) {
		return new Promise((resolve, reject) => {
			const ext = file.substr(file.lastIndexOf('.') + 1);
			this.requst('/assets/qn_up_info', {
					jm_type: '0',
					file_ext: ext
				}, 'GET', 'application/json', '59bcce6ed09fb5f5cbdf42418a3f9c99')
				.then((res) => {
					uni.uploadFile({
						url: res.data.up_url || 'https://up-z2.qiniup.com/',
						filePath: file,
						name: 'file',
						formData: {
							token: res.data.token,
							key: res.data.key
						},
						success: (uploadFileRes) => {
							resolve(res.data)
						},
						fail: (err) => {
							this.showError('上传失败！')
						}
					});
				});
		}).catch(err => {
			this.showError('未知错误,上传失败')
		})
	},
	// 复制文本
	copyText(text) {
		uni.setClipboardData({
			data: text + '',
			success: () => {
				this.showError('文本复制成功！')
			}
		});
	},
	// 获取文章
	getArtical(slug) {
		return new Promise((resolve, reject) => {
			this.requst('/gwc/user/wiki/' + slug, {
				slug: slug
			}).then(res => {
				resolve(res.data.body)
			})
		}).catch(err => {
			this.showError('未知错误！')
		})
	},
	downImg(url) {
		uni.showLoading({
			title: '下载中...'
		});
		uni.downloadFile({
			url: url,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: () => {
							uni.hideLoading();
							this.showError('保存成功')
						},
						fail: () => {
							uni.hideLoading();
							this.showError('保存失败')
						}
					});
				}
			},
			fail() {
				uni.hideLoading();
				this.showError('下载失败')
			}
		});
	},
	// 预览图片
	toPrewImgArr(arr, index) {
		let a = arr.map(item => {
			return item.url
		})
		this.toPreviewImg(a, index)
	},
	// 检验手机号是否合格
	isValidPhone(phone) {
		const regex = /^1[3-9]\d{9}$/;
		return regex.test(phone);
	}
}